package com.fenghongzhang.messenger_client;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


    //创建客户端的信使
    Messenger clientMessenger = new Messenger(new Handler(){
        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            String hello = data.getString("hello");
            Toast.makeText(MainActivity.this, hello, Toast.LENGTH_SHORT).show();

        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        Intent intent = new Intent();
        intent.setPackage("com.fenghongzhang.messager_server");
        intent.setAction("com.feng.message");

        ServiceConnection serviceConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                //服务端信使
                Messenger messenger = new Messenger(service);

                Message obtain = Message.obtain();
                Bundle bundle = new Bundle();
                bundle.putString("hi","你好");
                obtain.setData(bundle);

                //给message的replayto赋值
                obtain.replyTo = clientMessenger;

                //给服务发一个消息
                try {
                    messenger.send(obtain);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onServiceDisconnected(ComponentName name) {

            }
        };

        bindService(intent,serviceConnection,BIND_AUTO_CREATE);


    }
}
